//
//  AlivingViewController.m
//  meiyaya
//
//  Created by 张领瑞 on 2017/9/2.
//  Copyright © 2017年 ShiFeiEr. All rights reserved.
//

#import "AlivingViewController.h"
#import "PrefixHeader.pch"
#import "CollectionViewCell.h"
@interface AlivingViewController ()<SwipeViewDelegate,SwipeViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,HeaderRightBtnDelegate,ClassViewCellDelegate>
@property (strong,nonatomic) UICollectionViewFlowLayout *layout;
@property (strong,nonatomic) UICollectionView *collectionView;
@property (strong,nonatomic) SwipeView * swipeView;
@property (strong,nonatomic) NSMutableArray *bannerDataArray;
@property (strong,nonatomic) UIPageControl *currentPageControl;
@property (strong,nonatomic) NSTimer *myTimer;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *searchBtn;
@end

@implementation AlivingViewController


#pragma mark 跳转到searchCtr

- (IBAction)searchAction:(id)sender {
    
   SearchViewController *searchVC = (SearchViewController *)[self viewControllerInMStoryboardWithName:@"Main" WithIdentifier:@"SearchViewController"];
   self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:NO];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark ClassViewCellDelegate 点击分类的按钮事件回调
-(void)hadSelectedClassBtn:(UIButton *)sender{
    
    CategoryViewController *categoryVC = [[CategoryViewController alloc] initWithNibName:@"CategoryViewController" bundle:[NSBundle mainBundle]];
    switch (sender.tag) {
        case 101://跳转到课程
            categoryVC.url = CATEGORY_COURSE;
            break;
        case 102://跳转到讲师
            categoryVC.url = CATEGORY_LECTURER;
            break;
        case 103://跳转到会员
            categoryVC.url = CATEGORY_MEMBER;
            break;
        case 104://跳转到排行榜
            categoryVC.url = CATEGORY_RANKINGLIST;
            break;
        default:
            break;
    }
    
     [self.navigationController pushViewController:categoryVC animated:YES];

}

#pragma mark HeaderRightBtnDelegate 点击Sction的more按钮事件回调
-(void)rightMoreBtn:(UIButton *)sender{
    
    MoreViewController *moreCV = [[ MoreViewController alloc] init];
    switch (sender.tag) {
        case 1002:
            moreCV.classID = 1002;
            break;
        case 1003:
            moreCV.classID = 1003;
            break;
        case 1004:
            moreCV.classID = 1004;
            break;
        default:
            break;
    }
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:moreCV animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark LazyLoad
-(SwipeView *)swipeView{
    
    if (!_swipeView) {
        _swipeView = [[SwipeView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 180)];
        //设置代理
        _swipeView.dataSource = self;
        _swipeView.delegate = self;
        _swipeView.itemsPerPage = 1;
        _swipeView.pagingEnabled = YES;
        
        //设置居中对齐样式
        _swipeView.alignment = SwipeViewAlignmentCenter;
        //设置首尾循环
        _swipeView.wrapEnabled = YES;
        _swipeView.truncateFinalPage = YES;
        
        [_swipeView addSubview:self.currentPageControl];
    }
    return _swipeView;
}

-(NSMutableArray *)bannerDataArray{
    if (_bannerDataArray == nil) {
         _bannerDataArray = [[NSMutableArray alloc] init];
        [_bannerDataArray addObject:[UIImage imageNamed:@"5.png"]];
        [_bannerDataArray addObject:[UIImage imageNamed:@"5.png"]];
        [_bannerDataArray addObject:[UIImage imageNamed:@"5.png"]];
        [_bannerDataArray addObject:[UIImage imageNamed:@"5.png"]];
    }
    return _bannerDataArray;
}

- (UIPageControl *)currentPageControl{
    if (_currentPageControl == nil) {
        _currentPageControl = [[ UIPageControl alloc] init];
        _currentPageControl.frame = CGRectMake(120, 150, 100, 30);
        _currentPageControl.numberOfPages = self.bannerDataArray.count;
        _currentPageControl.currentPageIndicatorTintColor = [UIColor redColor];
        _currentPageControl.pageIndicatorTintColor = [UIColor whiteColor];
        _currentPageControl.center = CGPointMake(self.view.center.x, self.currentPageControl.center.y);
    }
    return _currentPageControl;
}

-(UICollectionViewLayout *)layout{
    if (_layout == nil) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
    }
    return _layout;
}

- (UICollectionView *)collectionView{
    
    if (_collectionView == nil) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, self.view.frame.size.height-kTABBAR_HEIGHT-kNAVIGATIONBAR_HEIGHT-19) collectionViewLayout:self.layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator = NO;
    }
    return _collectionView;
}

- (NSTimer *)myTimer{
    
    if (_myTimer == nil) {
       _myTimer = [NSTimer scheduledTimerWithTimeInterval:BANNERINTREVAL target:self selector:@selector(scrollToNextIndex) userInfo:nil repeats:YES];
     }
    return _myTimer;
}

#pragma mark 计时器执行方法
- (void)scrollToNextIndex
{
    NSInteger nextIndex = self.swipeView.currentItemIndex;
    nextIndex = (nextIndex + 1) % (self.bannerDataArray.count);
    [self.swipeView scrollToItemAtIndex:nextIndex duration:0.5];
}

- (void)startTimer
{
    [self stopTimer];
    [self.myTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:BANNERINTREVAL]];
}

- (void)pauseTimer
{
    if (![self.myTimer isValid]) {
        return;
    }
    [self.myTimer setFireDate:[NSDate distantFuture]];
}

- (void)stopTimer
{
    if ([self.myTimer isValid]) {
        [self.myTimer invalidate];
        self.myTimer = nil;
    }
}
-(void)resumeTimer
{
    if (![self.myTimer isValid]) {
        return;
    }
    [self.myTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:BANNERINTREVAL]];
}

#pragma mark 确定currentpagecontrol小标
-(void)swipeViewCurrentItemIndexDidChange:(SwipeView *)swipeView{
    self.currentPageControl.currentPage = self.swipeView.currentPage;
}


#pragma mark SwipeViewDataSource method

-(NSInteger)numberOfItemsInSwipeView:(SwipeView *)swipeView{
    
    return self.bannerDataArray.count;
}
-(UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view{
    
     if (view == nil) {
        UIImageView * view1 = [[UIImageView alloc] init];
     [view1 setImage:self.bannerDataArray[index]];
     view = view1;
     }else{
         [(UIImageView*)view setImage:self.bannerDataArray[index]];
     }
    return view;
}
#pragma mark SwipeViewDelegate method
-(CGSize)swipeViewItemSize:(SwipeView *)swipeView{
    
    return CGSizeMake(SCREENWIDTH, 180);
}

-(void)swipeView:(SwipeView *)swipeView didSelectItemAtIndex:(NSInteger)index{
    
    NSLog(@"点击了banner的第%ld个图",(long)index);
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if( BANNERINTREVAL > 0){
        [self startTimer];  //启动定时器
    }
}


# pragma mark UICollectionViewDataSourceDelegate method

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 5;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return 1;
    }
    if (section == 2 || section == 3) {
        return 4;
    }
    return 4;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell * cell;
    if (indexPath.section == 0) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SwipeViewCell" forIndexPath:indexPath];
        [cell addSubview:self.swipeView];
    }
    
    if (indexPath.section == 1) {
     ClassViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ClassViewCell" forIndexPath:indexPath];
        cell.delegate = self;
        //cell = cell;
        return cell;
        
    }
    if (indexPath.section == 2 || indexPath.section == 3) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    }
    if (indexPath.section ==4) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BznsInfoCollectionViewCell" forIndexPath:indexPath];
    }
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableView;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HeaderReusableView*   reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderReusableView" forIndexPath:indexPath];
        reusableView.delegate = self;
            if (indexPath.section == 2) {
                reusableView.rightMoreBtn.tag = 1002;
                reusableView.sectionTitleLabel.text = @"热门课程";
            }
            if (indexPath.section == 3) {
                reusableView.rightMoreBtn.tag = 1003;
                reusableView.sectionTitleLabel.text = @"会员课程";
            }
            if (indexPath.section == 4) {
                reusableView.rightMoreBtn.tag = 1004;
                reusableView.sectionTitleLabel.text = @"行业资讯";
            }
           return reusableView;
         }
    
     if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
          FooterReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterReusableView" forIndexPath:indexPath];
             return reusableView;
         }
   return  reusableView;
}

#pragma mark collectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 2:          //@"热门课程"
            
            break;
        case 3:         //@"会员课程"
            
            break;
        case 4:         //@"行业资讯"
        {
            DetailInfoViewController *detailInfoVC = [[DetailInfoViewController alloc] init];
            self.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:detailInfoVC animated:YES];
            self.hidesBottomBarWhenPushed = NO;
            break;}
        default:
            break;
    }
}


#pragma mark collectionViewLayoutDelegate
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 10, 0, 10);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 4) {
        return 1;
    }
    return 10;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(SCREENWIDTH, 180);
    }
    if (indexPath.section == 1) {
        return CGSizeMake(SCREENWIDTH, 80);
    }
    if (indexPath.section == 4) {
        return CGSizeMake(SCREENWIDTH, 100);
    }
  
   return ITEM_SIZE;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section == 0 || section == 1) {
        return CGSizeMake(SCREENWIDTH, 0);
    }
    return CGSizeMake(SCREENWIDTH, 36);
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(SCREENWIDTH,0);
    }
    return CGSizeMake(SCREENWIDTH, 10);
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self stopTimer];//退出时停止计时
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [ UIColor whiteColor];
   
    //添加collection到view
    [self.view addSubview:self.collectionView];
    
    //注册单元格、
    [self.collectionView registerNib:[UINib nibWithNibName:@"ClassViewCell" bundle:[NSBundle mainBundle]]forCellWithReuseIdentifier:@"ClassViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"CollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"SwipeViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"SwipeViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"BznsInfoCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"BznsInfoCollectionViewCell"];
    
   //注册头视图、脚视图
    [self.collectionView registerNib:[UINib nibWithNibName:@"HeaderReusableView" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderReusableView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"FooterReusableView" bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterReusableView"];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
